package com.scientific.research.gobang.service.superuser.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scientific.research.gobang.pojo.User;
import com.scientific.research.gobang.mapper.MatchMapper;
import com.scientific.research.gobang.mapper.SuperUserMapper;
import com.scientific.research.gobang.pojo.MatchMessage;
import com.scientific.research.gobang.pojo.SuperUser;
import com.scientific.research.gobang.utils.JwtUtils;
import com.scientific.research.gobang.service.SuperUserService;
import com.scientific.research.gobang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SuperUserServiceImpl implements SuperUserService {
    @Autowired
    SuperUserMapper superUserMapper;
    @Autowired
    MatchMapper matchMapper;
    @Autowired
    UserService userService;


    //返回管理员界面需要的比赛信息，显示前20场
    @Override
    public Map superUserMessage(Map map) {
        User user = userService.LodeUserMessage(map);
        Map<String, Object> result = new HashMap<>();
        Page<MatchMessage> pages = new Page<>(1, 20);
        matchMapper.selectPage(pages, null);
        List<MatchMessage> matchList = pages.getRecords();
        result.put("matches", matchList);
        result.put("user", (user.getEmail()));
        return result;
    }

    //管理员登录验证
    @Override
    public Map superUserVerify(User user) {
        HashMap<String, String> map = new HashMap<>();
        QueryWrapper<SuperUser> wrapper = new QueryWrapper<>();
        wrapper.eq("email", user.getEmail());

        SuperUser admin = superUserMapper.selectOne(wrapper);
        if (admin == null) {
            map.put("result", "EmailError");
        } else if (!DigestUtil.bcryptCheck(user.getPassword(), admin.getPassword()))//如果密码用Bcrypt解密失败就返回密码错误
        {
            map.put("result", "PasswordError");
        } else {
            map.put("result", "success");
            user.setPassword("");
            map.put("superUserToken", JwtUtils.getUserToken(user));//token有效期为一天
        }
        return map;
    }
}
